<style lang="less">
@import "../../styles/common.less";
.operate-column .ivu-btn-text{
    color:#008cd6;
}
.operate-column .ivu-btn-text:focus{
    box-shadow: none;
}
.blue-tag{
    margin:2px 4px;
    display: inline-block;
    padding:2px 6px;
    color:#fff;
    background:#2d8cf0;
}
</style>

<template>
  <div class="margin-top-10">
    <Row>
      <Select v-model="queryForm.ipc_id" style="width:150px;margin-right:10px" placeholder="请选择搜索设备">
        <Option v-for="item in ipcList" :value="item.ipc_id" :key="item.ipc_id">{{ item.ipc_name }}</Option>
      </Select>
      <Button @click="searchLibrary" type="primary">查询</Button>
      <Dropdown @on-click="handleBatchLibrary">
        <Button type="primary">
          批量操作
          <Icon type="arrow-down-b"></Icon>
        </Button>
        <DropdownMenu slot="list">
          <DropdownItem name="update">批量更新底库</DropdownItem>
          <DropdownItem name="delete">批量删除底库</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      <Button @click="emptyLibray" type="warning">清空设备底库</Button>
      <Button @click="loadBatchLog" style="margin-left:20px;">查看最近上传记录</Button>
    </Row>
    <div class="margin-top-10">
      <Table @on-selection-change="selectionChange" :columns="libraryColumn" :data="libraryData" :loading="tableLoading"></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="totalLibrary"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="getLibrary"
        show-total
      >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalLibrary}}条</Page>
    </Row>

    <Modal
      v-model="studentModal"
      v-bind:title="modalTitle"
      :scrollable="true"
      width="400px"
      class-name="vertical-center-modal"
      :mask-closable="false"
      >
      <Form
        :label-width="50"
        :model="studentInfo"
       >
        <!--照片-->
        <Row type="flex" justify="center" style="margin-bottom: 5px">
          <div style="margin-bottom: 10px">
            <img :src="'data:image/png;base64,'+studentInfo.u_hp" style="width:100px;height:100px;border-radius:50%" />
          </div>
        </Row>
        <Row type="flex" justify="space-between">
          <Col style="width: 48.5%">
            <FormItem label="姓名:">
              <span>{{studentInfo.u_nm}}</span>
            </FormItem>
            <FormItem label="性别:">
              <span>{{studentInfo.u_sx==1?'男':studentInfo.u_sx==0?'女':''}}</span>
            </FormItem>
            <FormItem label="学校:" v-show="studentInfo.s_school">
              <span>{{studentInfo.s_school}}</span>
            </FormItem>
            <FormItem label="邮箱:" v-show="studentInfo.u_em">
              <span>{{studentInfo.u_em}}</span>
            </FormItem>
          </Col>
          <Col style="width: 48.5%">
            <FormItem label="学号:">
              <span>{{studentInfo.s_num}}</span>
            </FormItem>
            <FormItem label="电话:" v-show="studentInfo.u_pn">
              <span>{{studentInfo.u_pn}}</span>
            </FormItem>
            <FormItem label="班级:" v-show="studentInfo.s_class">
              <span>{{studentInfo.s_class}}</span>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
          <Btn type="primary" @click="updateStudentLibraryInfo">更新到底库</Btn>
      </div>
    </Modal>

    <!-- 查看记录 -->
    <Modal
        v-model="batchLogModal"
        width="800px"
        title="上传记录">
        <Table :columns="batchLogColumn" :data="batchLogTableData"></Table>
        <div slot="footer"></div>
    </Modal>

    <!-- 底库详情 -->
    <Modal
      v-model="studentLibraryModal"
      title="底库详情"
      :scrollable="true"
      width="400px"
      class-name="vertical-center-modal"
      :mask-closable="false"
      >
      <Form
        :label-width="50"
        :model="studentLibraryInfo"
       >
        <!--照片-->
        <Row type="flex" justify="center" style="margin-bottom: 5px">
          <div style="margin-bottom: 10px">
            <img :src="'data:image/png;base64,'+studentLibraryInfo.PersonPhoto" style="width:100px;height:100px;border-radius:50%" />
          </div>
        </Row>
        <Row type="flex" justify="space-between">
          <Col style="width: 48.5%">
            <FormItem label="姓名:">
              <span>{{studentLibraryInfo.PersonName}}</span>
            </FormItem>
            <FormItem label="性别:">
              <span>{{studentLibraryInfo.Sex==1?'男':studentLibraryInfo.Sex==0?'女':''}}</span>
            </FormItem>
            <FormItem label="学校:" v-show="studentLibraryInfo.School">
              <span>{{studentLibraryInfo.School}}</span>
            </FormItem>
            <FormItem label="邮箱:" v-show="studentLibraryInfo.Email">
              <span>{{studentLibraryInfo.Email}}</span>
            </FormItem>
          </Col>
          <Col style="width: 48.5%">
            <FormItem label="学号:">
              <span>{{studentLibraryInfo.PersonNum}}</span>
            </FormItem>
            <FormItem label="电话:" v-show="studentLibraryInfo.Phone">
              <span>{{studentLibraryInfo.Phone}}</span>
            </FormItem>
            <FormItem label="班级:" v-show="studentLibraryInfo.Class">
              <span>{{studentLibraryInfo.Class}}</span>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
      </div>
    </Modal>
    <!-- <Modal v-model="uploadModal" @on-cancel="hideUploadModal">
      <div slot="header">
        <p>
          导入表格
          <span style="font-weight: 100;font-size: 12px;margin-left: 5px">
            (请严格按照
            <a :href="excelFile" download="模板.xlsx">模板</a>格式上传表格)
          </span>
        </p>
      </div>
      <HorizonUploader ref="uploader"></HorizonUploader>
      <div slot="footer">
        <Button type="primary" @click="handleUpload">上传</Button>
      </div>
    </Modal> -->
  </div>
</template>

<script>
import {
  getStudentById
} from "../../controllers/student";
import {
  getBatchLog
} from "../../controllers/batchLog";
import ipcSetting from '../../controllers/ipcSetting';
import HorizonUploader from "./components/HorizonUploader.vue";

import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
import Constant from "../../libs/constants";
import _ from "lodash";
import iconDelete from "../../images/delete.png";
import iconEdit from "../../images/edit.png";

import excelFile from "../../assets/staffExcel.xlsx";

import moment from "moment";

export default {
  name:'photoLibrary',
  components: {
    HorizonUploader,
    Tooltip,
    Btn
  },
  data() {
    return {
      tableLoading: true,
      queryForm:{
          ipc_id:''
      },
      pageSize: Constant.PAGE_SIZE,
      currentPage: 1,
      totalLibrary: 0,
      libraryColumn: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed:'left'
        },
        {
          title: "学生姓名",
          align: "center",
          key: "PersonName",
          width: 200
        },
        // {
        //   title: "学生ID",
        //   key: "PersonId",
        //   align: "center",
        //   width: 200
        // },
        {
          title: "集团名称",
          align: "center",
          key: "group_name",
          width: 200
        },
        {
          title: "校区名称",
          align: "center",
          key: "campus_name",
          width: 200
        },
        {
          title: "班级名称",
          align: "center",
          key: "class_name",
          width: 200
        },
        {
          title: "所属设备名称",
          align: "center",
          key: "belongDeviceName",
          width: 200
        },
        {
          title: "所属设备编号",
          key: "belongDeviceNum",
          align: "center",
          width: 200
        },
        {
          title: "操作",
          align: "center",
          fixed:'right',
          minWidth: 400,
          render: (h, { row, column, index }) => {
            return (
              <div class="operate-column">
                  <i-button
                    type="text"
                    onClick={() => this.handleViewStudent(row.PersonId)}
                  >查看学生详情</i-button>
                  <i-button
                    type="text"
                    onClick={() => this.handleViewLibrary(row)}
                  >查看底库信息</i-button>
                  <i-button 
                    type="text"
                    onClick={() => this.handleDelLibrary(row)}
                  >删除底库信息</i-button>
              </div>
            );
          }
        }
      ],
      libraryData: [],
      selectionRows:[],
      ipcList:[],
      modalTitle: "学生详情",
      uploadModal: false,
      excelFile: excelFile,

      // 学生详情
      studentModal:false,
      studentInfo: {
        _id:'',
        u_nm: "",
        u_sx: "",
        s_school: "",
        u_em: "",
        s_num: "",
        u_pn: "",
        u_hp:"",
        s_class:''
      },
      // 学生底库详情
      studentLibraryModal:false,
      studentLibraryInfo:{
        Address: "",
        Birthday: "",
        IDCard: "",
        Nation: "",
        PersonId: "",
        PersonName: "",
        PersonPhoto:'',
        Phone:"",
        PersonNum:"",
        School:'',
        Class:'',
        Email:''
      },

      batchLogModal:false,
      batchLogColumn:[
        {
          title:'名称',
          key:'type_name',
          align:'center',
          width:180,
        },
        {
          title:'上传时间',
          key:'c_at',
          align:'center',
          width:160,
          render: (h,{row})=>{
            return (
              <span>{row.c_at?moment(row.c_at).format('YYYY/MM/DD HH:mm:ss'):'-'}</span>
            )
          }
        },
        {
          title:'记录',
          key:'content',
          minWidth:200,
          render: (h,{row})=>{
            return h('span',{
                domProps:{
                  innerHTML: row.content
                }
              }
            )
          }
        }
      ],
      batchLogTableData:[]
    };
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    },
  },
  //待考虑：初次加载表格的时机
  created() {
    this.getIpcList();
  },
  methods: {
    getLibrary(page) {
      this.currentPage = page;
      this.tableLoading = true;
      this.loadLibraryData();
    },
    getIpcList(){
        ipcSetting.loadIpcList().then(res=>{
             this.tableLoading = false;
            this.ipcList = (res.data||[]).filter(item=>item.ipc_type==='Julong_jHD23')
            if(this.ipcList.length){
              this.queryForm.ipc_id = this.ipcList[0].ipc_id
              this.loadLibraryData()
            }
        })
    },
    loadBatchLog(){
      getBatchLog().then(res=>{
        if(res.code===0){
          this.batchLogTableData = res.data;
          this.batchLogModal = true
        }
      })
    },
    selectionChange(selection){
      this.selectionRows = selection
    },
    handleBatchLibrary(type){
      if(this.selectionRows.length<=0){
        return this.$Message.error('请选择底库信息')
      }
      switch (type) {
        case "update":
          this.handleBatchUpdate();
          break;
        case "delete":
          this.handleBatchDelete();
          break;
        default:
          return 
      }
    },
    handleBatchUpdate(){
      this.tableLoading = true
      const student_ids = this.selectionRows.map(item=>item.PersonId)
      ipcSetting.batchUpdateStudentLibrary({
          student_ids,
          ...this.queryForm
      }).then(res=>{
        this.tableLoading = false
        if(res.code===0){
          this.$Message.success(res.msg||'操作成功')
          this.loadLibraryData()
        }
      }).catch(err=>{
        this.tableLoading = false
        console.log(err)
      })
    },
    handleBatchDelete(){
      const student_ids = this.selectionRows.map(item=>item.PersonId)
      this.$Modal.confirm({
        title: "警告",
        content: "删除设备底库，将影响设备中学生的自动考勤功能，确定继续操作吗？",
        onOk: () => {
          this.tableLoading = true
          ipcSetting.batchDeleteStudentLibrary({
              student_ids,
              ...this.queryForm
          }).then(res=>{
            this.tableLoading = false
            if(res.code===0){
              this.$Message.success(res.msg||'操作成功')
              this.loadLibraryData()
            }
          }).catch(err=>{
            this.tableLoading = false
            console.log(err)
          })
        }
      });
    },
    handleViewStudent(id){
      this.tableLoading = true;
      this.modalTitle = "学生详情";
      getStudentById(id).then(res=>{
        this.tableLoading = false
        if(res.code===0){
          this.studentModal = true;
          this.studentInfo=res.data||{}
        }
      }).catch(()=>{
        this.tableLoading = false
      })
    },
    updateStudentLibraryInfo(){
      this.$Modal.confirm({
        title: "确认",
        content: "更新【" + this.studentInfo.u_nm + "】到设备底库吗？",
        onOk: () => {
          this.tableLoading = true
          ipcSetting.updateStudentLibraryInfo({ 
            ...this.studentInfo,
            ipc_id:this.queryForm.ipc_id,
           }).then(res => {
            this.tableLoading = false
            if (res.code === 0) {
              this.$Message.success("更新成功!");
              this.studentModal = false;
              this.loadLibraryData();
            } else {
              // this.$Message.error("更新失败!");
            }
          }).catch(()=>{
            this.tableLoading = false
          })
        }
      });
    },
    handleDelLibrary(row){
      this.$Modal.confirm({
        title: "警告",
        content: "删除【" + row.PersonName + "】底库信息，将影响该学生的自动考勤功能，确定继续操作吗？",
        onOk: () => {
          this.tableLoading = true
          ipcSetting.deleteStudentLibraryInfo({ 
            _id:row.PersonId,
            ipc_id:this.queryForm.ipc_id,
           }).then(res => {
            this.tableLoading = false
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.studentModal = false;
              this.loadLibraryData();
            }
          }).catch(()=>{
            this.tableLoading = false
          })
        }
      });
    },
    handleViewLibrary(row){
      this.tableLoading = true
      ipcSetting.getStudentLibraryInfo({
        student_id:row.PersonId,
        ipc_id:row.belongDeviceId
      }).then(res=>{
        this.tableLoading = false
        if(res.code === 0) {
           this.studentLibraryModal = true
           const personInfo = res.data.PersonInfo
           this.studentLibraryInfo =  {
              Address: personInfo.Address,
              Birthday: personInfo.Birthday,
              IDCard: personInfo.IDCard,
              Nation: personInfo.Nation,
              PersonId: personInfo.PersonId,
              PersonName: personInfo.PersonName,
              PersonPhoto:personInfo.PersonPhoto,
              Phone:personInfo.Phone,
              Sex:personInfo.Sex,
              PersonNum:personInfo.PersonExtension.PersonCode1,
              School:personInfo.PersonExtension.PersonCode2,
              Class:personInfo.PersonExtension.PersonCode3,
              Email:personInfo.PersonExtension.PersonData1,
           }
        }
      }).catch(()=>{
        this.tableLoading = false
      })
    },
    searchLibrary() {
      //to-do:检验关键词
      this.currentPage = 1;
      this.tableLoading = true;
      this.loadLibraryData();
    },
    loadLibraryData() {
      this.selectionRows = [];
      this.tableLoading = true;
      ipcSetting.getPhotoLibrary({
        page_num:this.currentPage, 
        page_size:this.pageSize, 
        ...this.queryForm
      })
      .then(json => {
        let { total, data, code } = transLibraryData(json);
        this.totalLibrary = total;
        this.libraryData = data;
        this.tableLoading = false;
      }).catch(err=>{
          console.log(err)
          this.tableLoading = false;
      })
    },
    emptyLibray(){
      if(!this.queryForm.ipc_id){
          return this.$Message.warning('请选择要清空的设备')
      }
      this.$Modal.confirm({
        title: "警告",
        content: "清空设备底库，将影响设备中所有学生的自动考勤功能，确定继续操作吗？",
        onOk: () => {
          this.tableLoading = true
          ipcSetting.emptyStudentLibrary({
              ...this.queryForm
          }).then(res=>{
            this.tableLoading = false
            if(res.code===0){
              this.$Message.success(res.msg||'操作成功')
              this.loadLibraryData()
            }
          }).catch(err=>{
            this.tableLoading = false
            console.log(err)
          })
        }
      });
    },
    handleUpload() {
      if (!this.$refs["uploader"].hasFile) {
        this.$Message.error("请先选择文件");
        return;
      }
      var formData = new FormData();
      formData.append("file", this.$refs["uploader"].file);
      uploadLibraryData(formData).then(json => {
        if (json.code == 0) {
          this.$Message.success(json.msg);
          this.hideUploadModal();
          this.loadLibraryData(this.currentPage);
        }
      });
    },
    hideUploadModal() {
      this.$refs["uploader"].reset();
      this.uploadModal = false;
    },
  }
};

function transLibraryData(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { total: 0, result: {}};
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined) {
    return { total: 0, result: {} };
  }

  let { total, result } = data;

  return {
    total,
    data: result
  };
}

</script>